package com.itbaizhan.controller;

import com.itbaizhan.dao.RedisDao;
import com.itbaizhan.result.BaseResult;
import com.itbaizhan.service.LoginServcie;
import com.itbaizhan.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

/**
 * @author spf
 * @date 2024/3/6
 * @time 15:02
 */

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginServcie loginServcie;
    @Autowired
    private RedisDao redisDao;

    @GetMapping("/sendYZM")
    public BaseResult sendYZM(@RequestParam("phone") String phone){
        loginServcie.sendYZM(phone);
        return BaseResult.ok();
    }

    @GetMapping("/sendMessage")
    public BaseResult sendMessage(@RequestParam("phone") String phone){
        String checkCode = RandomUtil.buildCheckCode(4);
        BaseResult baseResult = loginServcie.sendMessage(phone, checkCode);
        if (baseResult.getCode() == 200){
            redisDao.set(phone, checkCode);
            return BaseResult.ok();
        }else {
            return baseResult;
        }
    }

    @PostMapping("/login")
    public BaseResult<String> login(@RequestParam("phone") String phone, @RequestParam("code") String code){
        String login = loginServcie.login(phone, code);
        return BaseResult.ok(login);
    }

    @GetMapping("/getLoginUser")
    public BaseResult<String> getLoginUser(@AuthenticationPrincipal UserDetails userDetails){
        String username = userDetails.getUsername();
        return BaseResult.ok(username);
    }
}
